<template>
    <div class="filter">
        <div class="uploadBtn" v-if="localTypeUnit == 1">
            <el-select
                v-model="typeUnit"
                class="m-2"
                placeholder="请选择上传单位"
                style="width: 160px"
                :disabled="true"
            >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>

        <div class="uploadBtn">
            <el-date-picker
                v-model="dateStartTime"
                type="date"
                :disabled-date="disabledDate1"
            />
        </div>
        <div class="uploadBtn" style="line-height: 38rem">至</div>
        <div class="uploadBtn">
            <el-date-picker
                v-model="dateEndTime"
                type="date"
                :disabled-date="disabledDate2"
            />
        </div>
        <!-- <div class="uploadBtn">
            <el-date-picker v-model="timeDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                end-placeholder="结束时间"  />
        </div> -->
        <div class="uploadBtn">
            <el-button type="primary" @click="search">查询</el-button>
        </div>
        <el-popover
            :visible="visible"
            placement="bottom"
            :width="360"
            :trigger="'hover'"
        >
            <el-scrollbar style="height: 400px">
                <p><strong>强校验规则（禁止提交）：</strong></p>
                <p>1、进水NH3-N≥进水TN，出水NH3-N≥出水TN</p>
                <p>2、进水BOD≥5天前的进水COD，出水BOD≥5天前的出水COD</p>
                <p>3、出水SV30≥100</p>
                <p>4、粪大肠菌群采样日期需比日报日期早2天</p>
                <p><strong>提示规则（可选择提交）：</strong></p>
                <p>1、水温≤5或≥40</p>
                <p>2、进出水PH≤6或≥9</p>
                <p>3、出水SS≥10</p>
                <p>4、城北厂出水COD≥50，其他厂出水COD≥30</p>
                <p>5、城北厂、城东厂出水BOD≥10，其他厂出水BOD≥6</p>
                <p>6、进水BOD/5天前的COD的比值≤0.2或≥0.8</p>
                <p>7、进水COD≥500</p>
                <p>8、城北厂出水TN≥15，其他厂出水TN≥10</p>
                <p>9、城北厂出水NH3-N≥5，其他厂出水NH3-N≥1.5</p>
                <p>10、城北厂出水TP≥0.5，其他厂出水TP≥0.3</p>
                <p>11、进水TN≥45</p>
                <p>12、进水TP≥5</p>
                <p>13、进水NH3≥30</p>
                <p>14、粪大肠≥1000</p>
                <p>15、MLVSS/MLSS的比值≤0.2或≥0.8</p>
                <p>16、SV30≥98</p>
                <p>17、污泥含水率≤40或≥70</p>
                <p>18、DO≥11</p>
                <p>19、SVI≤30或≥150</p>
                <p>20、实数校验</p>
            </el-scrollbar>
            <template #reference>
                <div class="uploadBtn">
                    <el-button @click="visible = true" :icon="QuestionFilled"
                        >手工录入校验规则</el-button
                    >
                </div>
            </template>
        </el-popover>
    </div>
    <el-table
        :data="getValues"
        :show-header="false"
        border
        :span-method="objectSpanMethod"
        ref="tableList"
        size="small"
        :height="hHeight + 'px'"
    >
        <el-table-column
            prop="title"
            label=""
            :width="60"
            fixed=""
            align="center"
        >
            <template #default="scope">
                <span>{{ identifyResultList[scope.$index].title }}</span>
            </template>
        </el-table-column>
        <el-table-column
            v-for="(item, index) in getHeaders"
            :key="index"
            :prop="item"
            :fixed="index == 0"
            :width="index < 1 ? 80 : 60"
            align="center"
        >
            <template #default="scope">
                <span v-if="index == 0 || scope.$index == 0">{{
                    scope.row[item]
                }}</span>
                <el-input
                    v-else-if="index > 0"
                    v-model="scope.row[item]"
                    size="small"
                    @blur="blurFn(index, scope.$index, scope.row[item])"
                    @focus="focusFn(index, scope.$index)"
                    :disabled="isNoEdit()"
                />
                <!-- {{ index }}{{ scope.$index }} {{ scope.row[item] }} -->
            </template>
        </el-table-column>
    </el-table>
    <div class="uploadBtn" style="margin-bottom: 0">
        <el-button
            @click="submitEdit"
            type="primary"
            style="width: 212px; margin-top: 40rem"
            >提交</el-button
        >
    </div>
    <el-dialog v-model="dialogVisible" title="校验提示" width="500">
        <!-- <span>{{ checkResult }}</span> -->
        <div
            style="line-height: 1.5"
            v-html="checkResult.replace(/\n/g, '<br/>')"
        ></div>
        <div
            v-if="canSubmit"
            style="
                margin-top: 20px;
                display: flex;
                flex-direction: row;
                align-items: center;
            "
        >
            <el-icon size="18" color="#e6a23c"><WarningFilled /></el-icon
            ><span>数据有异常或超设计值，请确认是否继续提交</span>
        </div>
        <div
            v-else
            style="
                margin-top: 20px;
                display: flex;
                flex-direction: row;
                align-items: center;
            "
        >
            <el-icon size="18" color="#ff0000"><WarningFilled /></el-icon
            ><span>不合规数据，请修正后重新提交</span>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button
                    v-show="canSubmit"
                    type="primary"
                    @click="continueConfirm"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { onMounted, ref, computed, watch } from "vue";
import moment from "moment";
import dataListHttp from "@/https/dataList.js";
import ChartLineBar from "../charts/ChartLineBar.vue";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { ElMessage, ElMessageBox } from "element-plus";
import { WarningFilled, QuestionFilled } from "@element-plus/icons-vue";
const dateStartTime = ref(moment().startOf("month").format("YYYY-MM-DD"));
const dateEndTime = ref(moment().format("YYYY-MM-DD"));
const disabledDate1 = ref((time) => {
    return time.getTime() > Date.now();
});
const disabledDate2 = ref((time) => {
    return (
        time.getTime() < moment(dateStartTime.value) ||
        time.getTime() > Date.now()
    );
});
const emits = defineEmits(["submitEditEmit"]);
// const timeDate = ref([moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')])
const currentYear = ref(moment().format("YYYY"));
const localTypeUnit = ref(Storage.localGet("depId"));
const typeUnit = ref("6");
const username = ref(Storage.localGet("username"));
const options = ref([
    // { label: '全部', value: '1' },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const hHeight = ref(0);
const wWidth = ref(0);
const tableItemWidth = ref(0);
const option = ref({});
const chartTypeModel = ref("ssIn");
const chartTypeList = ref([
    { label: "处理水量", value: "treatedWaterQuantity", idx: 0 },
    { label: "水温", value: "waterTemperature", idx: 1 },
    { label: "PH进水", value: "phIn", idx: 2 },
    { label: "PH出水", value: "phOut", idx: 3 },
    { label: "SS进水", value: "ssIn", idx: 4 },
    { label: "SS出水", value: "ssOut", idx: 5 },
    { label: "COD进水", value: "codIn", idx: 6 },
    { label: "COD出水", value: "codOut", idx: 7 },
    { label: "BOD5进水", value: "bodIn", idx: 8 },
    { label: "BOD5出水", value: "bodOut", idx: 9 },
    { label: "TN进水", value: "tnIn", idx: 10 },
    { label: "TN出水", value: "tnOut", idx: 11 },
    { label: "NH3-N进水", value: "nhNIn", idx: 12 },
    { label: "NH3-N出水", value: "nhNOut", idx: 13 },
    { label: "TP进水", value: "tpIn", idx: 14 },
    { label: "TP出水", value: "tpOut", idx: 15 },
    { label: "粪大肠菌群", value: "cufOut", idx: 16 },
    { label: "色度", value: "chroma", idx: 17 },
]);
const chartTypeItem = ref([
    {
        type: "line",
        code: "treatedWaterQuantity",
        name: "处理水量",
        linerColor: ["#b5bfd8", "#b5bfd8"],
    },
]);
const chartType = ref([
    {
        type: "line",
        code: "treatedWaterQuantity",
        name: "处理水量",
        linerColor: ["#b5bfd8", "#b5bfd8"],
    },
    {
        type: "line",
        code: "waterTemperature",
        name: "水温",
        linerColor: ["#3ea7ea", "#3ea7ea"],
    },
    {
        type: "line",
        code: "phIn",
        name: "PH进水",
        linerColor: ["#bdf5e8", "#bdf5e8"],
    },
    {
        type: "line",
        code: "phOut",
        name: "PH出水",
        linerColor: ["#9cf7b4", "#9cf7b4"],
    },
    {
        type: "line",
        code: "ssIn",
        name: "SS进水",
        linerColor: ["#76da91", "#76da91"],
    },
    {
        type: "line",
        code: "ssOut",
        name: "SS出水",
        linerColor: ["#63b2ee", "#63b2ee"],
    },
    {
        type: "line",
        code: "codIn",
        name: "COD进水",
        linerColor: ["#f89588", "#f89588"],
    },
    {
        type: "line",
        code: "codOut",
        name: "COD出水",
        linerColor: ["#f8cb7f", "#f8cb7f"],
    },
    {
        type: "line",
        code: "bodIn",
        name: "BOD5进水",
        linerColor: ["#7898e1", "#7898e1"],
    },
    {
        type: "line",
        code: "bodOut",
        name: "BOD5出水",
        linerColor: ["#7cd6cf", "#7cd6cf"],
    },
    {
        type: "line",
        code: "tnIn",
        name: "TN进水",
        linerColor: ["#eddd86", "#eddd86"],
    },
    {
        type: "line",
        code: "tnOut",
        name: "TN出水",
        linerColor: ["#efa666", "#efa666"],
    },
    {
        type: "line",
        code: "nhNIn",
        name: "N进水",
        linerColor: ["#63b2ee", "#63b2ee"],
    },
    {
        type: "line",
        code: "nhNOut",
        name: "NH3-N出水",
        linerColor: ["#9987ce", "#9987ce"],
    },
    {
        type: "line",
        code: "tpIn",
        name: "TP进水",
        linerColor: ["#9192ab", "#9192ab"],
    },
    {
        type: "line",
        code: "tpOut",
        name: "TP出水",
        linerColor: ["#76da91", "#76da91"],
    },
    {
        type: "line",
        code: "cufOut",
        name: "粪大肠菌群",
        linerColor: ["#89caf2", "#89caf2"],
    },
    {
        type: "line",
        code: "chroma",
        name: "色度",
        linerColor: ["#89caf2", "#89caf2"],
    },
]);
const chartTypeModelChange = (item, label) => {
    console.log(item, label);
    let idx = chartTypeList.value.findIndex((t) => {
        return t.value == item;
    });
    console.log(idx);
    chartTypeItem.value[0] = chartType.value[idx];
};
const unit = ref(["单位:mg/L"]);
const chartList = ref([]);
const uploadInitDataList = ref([]);
const uploadDataList = ref([]);

onMounted(() => {
    // nextTick(() => {
    hHeight.value = document.documentElement.clientHeight - 420;
    wWidth.value = document.documentElement.clientWidth - 296;
    // })
    initTable();
});
const initDate = ref([]);
const initTable = () => {
    initDate.value = [];
    resultList.value = [];
    uploadDataList.value = [];
    uploadInitDataList.value = [];
    // 计算选中日期相隔天数
    let startTime = moment(dateStartTime.value);
    let endTime = moment(dateEndTime.value);
    let tableDay = endTime.diff(startTime, "day");
    if (tableDay <= 31) {
        tableItemWidth.value = wWidth.value / (tableDay + 10);
    } else {
        tableItemWidth.value = wWidth.value / 41;
    }
    for (let i = 0; i <= tableDay; i++) {
        initDate.value.push(
            moment(dateStartTime.value).add(i, "day").format("MM-DD")
        );
        resultList.value.push({
            entryDate: moment(dateStartTime.value)
                .add(i, "day")
                .format("YYYYMMDD"),
            depId: typeUnit.value,
            date: moment(dateStartTime.value).add(i, "day").format("MM-DD"),
            entryDate: moment(dateStartTime.value)
                .add(i, "day")
                .format("YYYYMMDD"),
            do1: "",
            do2: "",
            mlss1: "",
            mlss2: "",
            mlvss1: "",
            mlvss2: "",
            sv1: "",
            sv2: "",
            svi1: "",
            svi2: "",
            containWater1: "",
        });
    }

    getWaterDateList();
};
const getWaterDateList = () => {
    let params = {
        depId: typeUnit.value,
        // "depId": 4,
        startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
        endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
        auditStatus: "1",
    };
    dataListHttp.queryCraft(params).then((res) => {
        console.log(res);
        for (let key in res.data.data) {
            if (initDate.value.includes(key)) {
                let idx = initDate.value.findIndex((item) => {
                    return item === key;
                });
                res.data.data[key].entryDate = resultList.value[idx].entryDate;
                res.data.data[key].depId = typeUnit.value;
                resultList.value[idx] = res.data.data[key];
            }
        }
        uploadDataList.value = JSON.parse(JSON.stringify(resultList.value));
        uploadInitDataList.value = JSON.parse(JSON.stringify(resultList.value));
        chartList.value = resultList.value;

        // getWaterOtherDateList()
    });
};

const identifyResultList = ref([
    { title: "日期", label: "rq" },
    { title: "DO(mg/L)", label: "do1" },
    { title: "DO(mg/L)", label: "do2" },
    { title: "MLSS(mg/L)", label: "mlss1" },
    { title: "MLSS(mg/L)", label: "mlss2" },
    { title: "SV30(%)", label: "sv1" },
    { title: "SV30(%)", label: "sv2" },
    { title: "SVI(mL/g)", label: "svi1" },
    { title: "SVI(mL/g)", label: "svi2" },
    { title: "MLVSS(mg/L)", label: "mlvss1" },
    { title: "MLVSS(mg/L)", label: "mlvss2" },
    { title: "污泥含水率(%)", label: "containWater1" },
]);
const resultList = ref([]);
const headersList = ref([
    {
        prop: "date",
        label: "日期",
    },
    {
        prop: "do1",
        label: "南",
    },
    {
        prop: "do2",
        label: "北",
    },
    {
        prop: "mlss1",
        label: "南",
    },
    {
        prop: "mlss2",
        label: "北",
    },
    {
        prop: "sv1",
        label: "南",
    },
    {
        prop: "sv2",
        label: "北",
    },
    {
        prop: "svi1",
        label: "南",
    },
    {
        prop: "svi2",
        label: "北",
    },
    {
        prop: "mlvss1",
        label: "南",
    },
    {
        prop: "mlvss2",
        label: "北",
    },
    {
        prop: "containWater1",
        label: "板框压滤",
    },
]);
const getUnitTypeName = computed(() => {
    return typeUnit.value == 1
        ? "总公司"
        : typeUnit.value == 2
        ? "星沙厂"
        : typeUnit.value == 3
        ? "城西厂"
        : typeUnit.value == 4
        ? "城北厂"
        : typeUnit.value == 4
        ? "城南厂"
        : "城东厂";
});
const getHeaders = computed(() => {
    return uploadDataList.value.reduce(
        (pre, cur, index) => pre.concat(`value${index}`),
        ["title"]
    );
});
const getValues = computed(() => {
    return headersList.value.map((item) => {
        return uploadDataList.value.reduce(
            (pre, cur, index) =>
                Object.assign(pre, { ["value" + index]: cur[item.prop] }),
            { title: item.label }
        );
    });
});
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
    let len = uploadDataList.value.length;
    if (rowIndex === 0 || rowIndex === 11) {
        if (columnIndex === 0) {
            return [1, 2];
        } else if (columnIndex === 1) {
            return [0, 0];
        }
    }
    if (columnIndex === 0) {
        if (rowIndex === 1) {
            return {
                rowspan: 2,
                colspan: 1,
            };
        } else if (rowIndex === 3) {
            return {
                rowspan: 2,
                colspan: 1,
            };
        } else if (rowIndex === 5) {
            return {
                rowspan: 2,
                colspan: 1,
            };
        } else if (rowIndex === 7) {
            return {
                rowspan: 2,
                colspan: 1,
            };
        } else if (rowIndex === 9) {
            return {
                rowspan: 2,
                colspan: 1,
            };
        } else if (rowIndex === 11) {
            return {
                rowspan: 1,
                colspan: 1,
            };
        } else {
            return {
                rowspan: 0,
                colspan: 0,
            };
        }
    }
};
const search = () => {
    initTable();
};

const blurFn = (row, column, item) => {
    console.log(row, column);
    uploadDataList.value[row - 1][identifyResultList.value[column].label] =
        item;
    console.log(uploadDataList.value);
};

const focusFn = (row, column) => {
    window.addEventListener(
        "paste",
        (event) => {
            event = event || window.event;
            const clipdata = event.clipboardData || window.clipboardData;
            const value = clipdata.getData("text/plain");
            console.log(value);

            let clipboardList = value.split("\r\n");
            clipboardList.forEach((item, ind) => {
                let itemList = item.split("\t");
                clipboardList[ind] = itemList;
            });
            setTimeout(() => {
                console.log("1111", clipboardList);
                clipboardList.forEach((item, ind) => {
                    item.forEach((n, m) => {
                        n = n.replace(/\s+/g, "");
                        n = n.replace(/(\r\n|\n|\r)/gm, "");
                        console.log(
                            row - 1 + m < uploadDataList.value.length,
                            uploadDataList.value.length
                        );
                        if (row - 1 + m < uploadDataList.value.length) {
                            uploadDataList.value[row - 1 + m][
                                identifyResultList.value[column + ind].label
                            ] = n;
                        }
                    });
                });
            });
        },
        { once: true }
    );
};
const isNoEdit = () => {
    return false;
};

watch(
    uploadInitDataList,
    (newVal, oldVal) => {
        console.log("11111", newVal);
    },
    { deep: true }
);
watch(
    uploadDataList,
    (newVal, oldVal) => {
        console.log("222", newVal);
    },
    { deep: true }
);
const checkResult = ref("");
const dialogVisible = ref(false);
const canSubmit = ref(false);
const submitEdit = () => {
    setTimeout(() => {
        let compare1 = {
            obj: uploadInitDataList.value,
        };
        let compare2 = {
            obj: uploadDataList.value,
        };
        console.log(uploadInitDataList.value, uploadDataList.value);
        if (JSON.stringify(compare1) == JSON.stringify(compare2)) {
            ElMessage({
                message: "没有检测到数据修改",
                type: "warning",
            });
        } else {
            uploadDataList.value.forEach((item) => {
                item.date = item.entryDate;
            });
            let params = {
                dailyPOList: uploadDataList.value,
                username: username.value,
            };
            dataListHttp.dailyCheckCraft(params).then((res) => {
                console.log(res);
                if (res.data.code == 200) {
                    dataListHttp.entryDailyCraft(params).then((res) => {
                        console.log(res);
                        if (res.data.code == 200) {
                            ElMessage({
                                message: "修改成功",
                                type: "success",
                            });
                            initTable();
                            emits("submitEditEmit");
                        } else {
                            ElMessage({
                                message: "修改失败,请重新提交",
                                type: "error",
                            });
                        }
                    });
                } else {
                    dialogVisible.value = true;
                    checkResult.value = res.data.msg || "";
                    if (res.data.code != 500) {
                        canSubmit.value = true;
                    }
                }
            });
        }
    }, 100);
};
const continueConfirm = () => {
    uploadDataList.value.forEach((item) => {
        item.date = item.entryDate;
    });
    let params = {
        dailyPOList: uploadDataList.value,
        username: username.value,
    };
    dataListHttp.entryDailyCraft(params).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
            ElMessage({
                message: "提交成功",
                type: "success",
            });
            initTable();
            emits("submitEditEmit");
        } else {
            ElMessage({
                message: "提交失败,请重新提交",
                type: "error",
            });
        }
    });
};
const resetEdit = () => {
    initTable();
};
const exportDataList = () => {
    let params = {
        // "depId": 4,
        depId: typeUnit.value,
        startTime: moment(dateStartTime.value).format("YYYY-MM-DD 00:00:00"),
        endTime: moment(dateEndTime.value).format("YYYY-MM-DD 23:59:59"),
    };
    dataListHttp.exportAssay(params).then((response) => {
        console.log(response);
        const content = response.data;
        const blob = new Blob([content], { type: "application/ms-excel" });
        let fileName = `化验数据.xls`;
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
};
</script>

<style scoped lang="less">
.waterYield {
    background: #fff;
    height: 100%;
}

.filter {
    display: flex;
    align-items: center;
}

.uploadBtn {
    text-align: left;
    margin-bottom: 40rem;
    margin-right: 20rem;
}

.chart {
    margin-top: 60px;
}

.unit {
    text-align: right;
    font-size: 14px;
    line-height: 2;
    padding-right: 40px;
    margin-top: -20px;
}
</style>
